package com.vilynn.interview.wechatofficial.sort;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Question2
 *
 * @author Weilin Wang
 * @since 2020/11/18
 */
public class Question2 {

    private static final int number = 3;

    private static final Executor executor = Executors.newFixedThreadPool(number);

    private static final List<MyThread> threads = new ArrayList<>();

    public static void main(String[] args) {
//        executor.execute(() -> {
//            // 每个任务执行
//        });

        for (int i = 0; i < number; i++) {
            MyThread thread = new MyThread(i);
            threads.add(thread);
            thread.start();
        }
    }

    private static class MyThread extends Thread {

        private int order;

        public MyThread(int order) {
            this.order = order;
        }

        @Override
        public void run() {
            Thread t = Thread.currentThread();
            try {
                System.out.println(String.format("id:%s name:%s 输出%s", t.getId(), t.getName(), "~~~~开始执行任务"));

                if (order == 0) {
                    throw new IllegalAccessException(String.format("id:%s name:%s 输出%s", t.getId(), t.getName(), "报错了"));
                }

                System.out.println(String.format("id:%s name:%s 输出%s", t.getId(), t.getName(), "查询用户"));
//                Thread.sleep(100);

                System.out.println(String.format("id:%s name:%s 输出%s", t.getId(), t.getName(), "查询库存"));
//                Thread.sleep(120);

                System.out.println(String.format("id:%s name:%s 输出%s", t.getId(), t.getName(), "查询订单"));
//                Thread.sleep(90);

                System.out.println(String.format("id:%s name:%s 输出%s", t.getId(), t.getName(), "~~~~结束"));

//            } catch (InterruptedException e) {
//                e.printStackTrace();
            } catch (Throwable e) {
                e.printStackTrace();
                for (MyThread thread : threads) {
                    if (thread != t) {
                        thread.cancel();
                    } else {
                        System.out.println(String.format("id:%s name:%s 输出%s", this.getId(), this.getName(), "~~~~不取消"));
                    }
                }
            }
        }

        private void cancel() {
            System.out.println(String.format("id:%s name:%s 输出%s", this.getId(), this.getName(), "~~~~任务取消了"));
            this.interrupt();
        }
    }

}
